<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SERVER['HTTP_REFERER'])
{
    $refer = parse_url($_SERVER['HTTP_REFERER']);
    if( ! in_array($refer['host'], array('www.ppuying.com','www.ppuying.dev')))
    {
        exit;
    }
    $file_path = $_SERVER['DOCUMENT_ROOT'].(string) $_POST['file_path'];
    $down_name = $_POST['down_name'];

    $ua = $_SERVER["HTTP_USER_AGENT"];

    $encoded_filename = urlencode($down_name);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);
    if(is_file($file_path))
    {
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private",false);
        header("Content-type: application/force-download");

        if (preg_match("/MSIE/", $ua))
        {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
        }
        else if (preg_match("/Firefox/", $ua))
        {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $down_name . '"');
        }
        else
        {
            header('Content-Disposition: attachment; filename="' . $down_name . '"');
        }

        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($file_path));
        readfile($file_path);
    }
}
